package xyz.zhzby.cyzx.oj.config;

import io.swagger.annotations.ApiModel;
import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.activemq.command.ActiveMQQueue;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jms.connection.CachingConnectionFactory;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.listener.SimpleMessageListenerContainer;
import xyz.zhzby.cyzx.oj.messenger.MessageReceiver;

/**
 * @author zby
 * @date 2022/02/05
 */
@ApiModel("MQ自定义组件")
@Configuration
public class MyBeans {

    @Value("${spring.activemq.broker-url}")
    private String brokerUrl;

    @Bean
    public ActiveMQConnectionFactory amqConnectionFactory() {
        return new ActiveMQConnectionFactory(brokerUrl);
    }

    @Bean
    public CachingConnectionFactory connectionFactory() {
        return new CachingConnectionFactory(amqConnectionFactory());
    }

    @Bean
    public ActiveMQQueue defaultDestination() {
        return new ActiveMQQueue("cyzxSubmissionTaskQueue");
    }

    @Bean
    public JmsTemplate jmsTemplate() {
        JmsTemplate jmsTemplate = new JmsTemplate();
        jmsTemplate.setConnectionFactory(connectionFactory());
        jmsTemplate.setDefaultDestination(defaultDestination());
        return jmsTemplate;
    }

    @Bean
    public SimpleMessageListenerContainer simpleMessageListenerContainer() {
        SimpleMessageListenerContainer simpleMessageListenerContainer = new SimpleMessageListenerContainer();
        simpleMessageListenerContainer.setConnectionFactory(connectionFactory());
        simpleMessageListenerContainer.setDestinationName("cyzxJudgeResultQueue");
        simpleMessageListenerContainer.setMessageListener(messageReceiver1());
        return simpleMessageListenerContainer;
    }

    @Bean
    public MessageReceiver messageReceiver1() {
        return new MessageReceiver();
    }
}
